/**
 * Copyright (C)  Gadglet .
 *
 * This file is part of Gadglet
 *
 * Gadglet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gadglet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Gadglet. If not, see <http://www.gnu.org/licenses/>.
 */

package com.gadglet.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gadglet.core.GadgletRequestWrapper;
import com.gadglet.core.GadgletResponse;
import com.gadglet.core.RequestException;
import com.gadglet.data.DomainUser;
import com.gadglet.data.DomainUserUtils;
import com.gadglet.data.Gadget;
import com.gadglet.data.GadgetUtils;
import com.gadglet.data.RegistrationToken;
import com.gadglet.data.RegistrationTokenUtils;
import com.gadglet.data.utils.DomainUserStatus;
import com.gadglet.params.GadgetType;
import com.gadglet.params.ReqErrorTypes;
import com.gadglet.params.SharedConstants;
import com.gadglet.util.UrlUtils;
import com.google.appengine.api.NamespaceManager;
import com.google.appengine.api.oauth.OAuthRequestException;
import com.google.appengine.api.oauth.OAuthService;
import com.google.appengine.api.oauth.OAuthServiceFactory;
import com.google.appengine.api.users.User;
import com.google.gson.Gson;

public class OauthRequestServlet extends BasicRequestServlet {

	private static final long serialVersionUID = 17583894573489L;
	Logger log = Logger.getLogger(this.getClass().getName());

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		checkUser(request, response);

	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		checkUser(request, response);

	}

	private void checkUser(HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse) {

		GadgletResponse gadgetServerResponse = new GadgletResponse();

		GadgletRequestWrapper platformRequestWrapper = new GadgletRequestWrapper(
				httpServletRequest);

		if (!(platformRequestWrapper.getParameter("ignoreJson") != null && UrlUtils
				.isOnDevPort8888(platformRequestWrapper)))
			setResponseHeaders(httpServletResponse);

		boolean userIsValid = false;
		try {
			userIsValid = validateOauthUser(platformRequestWrapper,
					gadgetServerResponse);
			
			// load gadget
			Gadget g = GadgetUtils.getGadget(platformRequestWrapper.getGadgetName());
			
			if(g==null || g.getGadgletType()==null || !g.getGadgletType().equals(GadgetType.BIZLET.getGadgetType()))
				throw new RequestException(
						ReqErrorTypes.UNRECOGNIZED_GADGET);
			else
				platformRequestWrapper.setRequestedGadget(g);

		} catch (RequestException e) {
			userIsValid = false;
			gadgetServerResponse.setError(e);
		} catch (Exception e) {
			userIsValid = false;
			gadgetServerResponse.setError(new RequestException(
					ReqErrorTypes.REQUEST_FAILED));
			printStackTrace(e);
		}

		if (userIsValid)
			performRequest(platformRequestWrapper, gadgetServerResponse,
					httpServletResponse);

		else {

			PrintWriter out = null;
			try {
				out = httpServletResponse.getWriter();
				Gson gson = new Gson();
				out.print(gson.toJson(new JsonEnvelope(gadgetServerResponse)));
			} catch (IOException e) {

				log.warning(e.getMessage());
			}

		}

	}

	protected boolean validateOauthUser(
			GadgletRequestWrapper platformRequestWrapper,
			GadgletResponse jsonResponse) throws RequestException {
		// need to check session for existing user

		boolean userLogin = false;
		User user = null;
		DomainUser domainUser = null;

		domainUser =  platformRequestWrapper.getCurrentDomainUser();

		try {
			OAuthService oauth = OAuthServiceFactory.getOAuthService();
			user = oauth.getCurrentUser();
			userLogin = true;


		} catch (OAuthRequestException e) {
			printStackTrace(e);
			throw new RequestException(ReqErrorTypes.USER_NOT_LOGGEDIN);

		}
		// in case the user changed his id during session (possible ?)
		if (domainUser != null && !user.getUserId().equals(domainUser.getId()))
			domainUser = null;

		if (domainUser != null) {
			NamespaceManager.set(domainUser.getAccount());
			return true;
		}


		
		domainUser = DomainUserUtils.getMyDomainUserWithOauth();
		// set user in session
		
		if (platformRequestWrapper != null && domainUser != null) {
					
			if (domainUser.getAccount() == null)
				throw new RequestException(ReqErrorTypes.USER_MISSING_ACCOUNT);
			if (domainUser.getStatus() != DomainUserStatus.ACTIVE.getUserStatus())
				throw new RequestException(ReqErrorTypes.USER_NOT_ACTIVE);
			
			platformRequestWrapper.getSession().setAttribute("domainUser",
					domainUser);
			NamespaceManager.set(domainUser.getAccount());
			return true;
		}
		
		
		if (domainUser == null) 
		{
			// Registration

			RegistrationToken token = null;
			// in case of SIGNED
			if (userRegistrationMethod.equalsIgnoreCase(SharedConstants.registrationMethodSigned))
				jsonResponse.addCustomFieldError(SharedConstants.registrationProcessParamName,
						SharedConstants.registrationDoSigned);

			else 
			{
			
				String tokenId = null;
				// work on token created in the current session

				if (platformRequestWrapper.getRegistrationTokenId() != null) {
					tokenId = platformRequestWrapper.getRegistrationTokenId();
					try {
						token = RegistrationTokenUtils.updateTokenForOauth(
								tokenId, user);
					} catch (Exception e) {
						printStackTrace(e);

					}
				}
				if (token == null) {
			
					try {
						token = RegistrationTokenUtils.createNew(user);

					} catch (Exception e) {
						printStackTrace(e);;
					}
				}

				//
				if (token != null) {
					jsonResponse.addCustomFieldError(
							SharedConstants.registrationTokenParamName,
							token.getTokenID());

					if (!token.isOpenSocialReady())
						jsonResponse.addCustomFieldError(
								SharedConstants.registrationProcessParamName,
								SharedConstants.registrationDoSigned);
				}
			}

			if (token != null)
				throw new RequestException(ReqErrorTypes.USER_NOT_REGISTERED);
			else
				throw new RequestException(ReqErrorTypes.REQUEST_FAILED);
		}

		return userLogin;
	}
}
